<?php
/**
 * DotHerbert
 *
 * @package    core
 * @subpackage config
 * @copyright  2009 extreme-programmers
 * @license    http://dotherbert.extreme-programmers.com/license   BSD License
 * @version    $Id: PropertyParser.php 44 2009-08-28 19:02:51Z johannes.trink@extreme-programmers.com $
 */

namespace dotherbert\core\config;

/**
 * Property parser
 *
 * @package    core
 * @subpackage config
 * @author     Johannes Trink <johannes.trink@extreme-programmers.com>
 */
class PropertyParser
{
    private $config, $path;

    /**
     * Constructor
     *
     * @param string $path
     */
    public function __construct($path)
    {
        $this->path = $path;
    }

    /**
     * Get path
     *
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Parse
     *
     * @param string $section
     *
     * @return array
     */
    public function parse($section)
    {
        if (null === $this->config) {
            $properties = @parse_ini_file($this->getPath(), true);
            if (false === $properties) {
                throw new PropertyParserException('failed to open config file: no such file');
            }
            $this->config = array();
            foreach ($properties as $sectionKey => $data) {
                $sectionParts = explode(':', $sectionKey);
                $countSectionParts = count($sectionParts);

                if (2 == $countSectionParts) {
                    $data[';extends'] = trim($sectionParts[1]);
                } elseif (2 < $countSectionParts) {
                    throw new PropertyParserException('multiple inheritance is not supported');
                }
                $this->config[trim($sectionParts[0])] = $data;
            }

            foreach ($this->config as $sectionKey => $data) {
                if (isset($data[';extends'])) {
                    $parentSection = $data[';extends'];
                    $this->config[$sectionKey] = array_merge($this->config[$parentSection], $this->config[$sectionKey]);
                    unset($this->config[$sectionKey][';extends']);
                }
            }
        }

        return $this->config[$section];
    }
}